<template>
   <div class='sub-category'>
    <div class="container">
      <!-- 自己封装的多选框 -->
      <!-- 面包屑 -->
      <SubBread />
      <!-- 筛选区 -->
      <SubFilter @checked='objChange'/>
      <!-- 多选框+商品展示 -->
      <div class="goods-list">
            <SubSort @objChange='objChange'></SubSort>
        <ul>
          <li v-for="item in list" :key="item.id">
            <GoodsItem :goods="item"></GoodsItem>
          </li>
        </ul>
        <XtxInfiniteLoading @infinite='getList' :loading='loading' :finished='finished'/>
      </div>
    </div>
  </div>
</template>
<script>
import { findSubCategoryGoods } from '@/api/category'
import XtxInfiniteLoading from '@/components/library/xtx-infinite-loading.vue'
import GoodsItem from './components/goods-item.vue'
import SubBread from './components/sub-bread.vue'
import SubFilter from './components/sub-filter.vue'
import SubSort from './components/sub-sort.vue'
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
export default {
  components: { SubBread, SubFilter, SubSort, GoodsItem, XtxInfiniteLoading },
  name: 'SubCategory',
  setup () {
    const route = useRoute()
    // 下拉加载的2个变量
    const loading = ref(false)
    const finished = ref(false)
    // 发送请求的页码和页容量
    let data = {
      page: 1,
      pageSize: 20
    }
    const list = ref([])
    // 监听ID，在不同二级选项切换的时候重置页码
    watch(() => route.params.id, (id) => {
      if (route.path === `/category/sub/${id}`) {
        list.value = []
        finished.value = false
        data = {
          categoryId: id,
          page: 1,
          pageSize: 20
        }
      }
    }, { immediate: true })
    const getList = async () => {
      loading.value = true
      const { result } = await findSubCategoryGoods(data)
      loading.value = false
      data.page++
      list.value.push(...result.items)
      if (result.items < data.pageSize) {
        finished.value = true
      }
    }
    // 从筛选页面传过来的数据
    const objChange = (val) => {
      list.value = []
      finished.value = false
      data = {
        ...data,
        ...val,
        page: 1
      }
      getList()
    }
    return { objChange, getList, loading, finished, list }
  }
}
</script>
<style scoped lang='less'>
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
